/**
 * Created by lwy on 2017/5/21.
 */

var remember;
var twice = false;
var verifyCode;
//$(function(){
//    if (typeof localStorage === 'object') {
//        try {
//            alert('支持');
//        } catch (e) {
//            alert('不支持');
//        }
//    }
//})
//点击验证码登录
$('#codelogin').click(function(){
    $('#passloginbox').hide();
    $('#codeloginbox').show();
    $('#login-button2').show();
    $('#phoneImg').attr('src','../img/login2-user2.png');
    $('#phoneImg').css({'width':'12px','height':'18px'})
    $('.code-button').show();
    $('#login-button1').hide();
    $(this).addClass('login2-active');
    $(this).siblings().removeClass('login2-active');
    ifOldUser();
})
var userId = '';
var isdzp = getItem('isdzp');
//判断是否为老用户
$(function () {
    userId = getItem('userId');

    if(userId==null||userId==undefined||userId==""){

    }else{
        document.getElementById('phone').oninput=function () {
            if($('#codelogin').hasClass('login2-active')){
                ifOldUser();
            }
            if($(this).val().length==11){
                $('#password').focus();
            }
        }
    }
})

function ifOldUser() {
    if($('#phone').val().length==11){
        //检查新老用户
        $.ajax({
            url:'/user/checkIfNewUser.json',
            dataType:'json',
            data:{
                mobile:$('#phone').val(),
            },
            type:'post',
            success:function (data) {
                //code=1未注册 code=0错误信息 code=-1已注册
                if(data.code==1){
                    userId = getItem('userId');
                    $.ajax({
                        url:'/user/userMSG.json',
                        dataType:'json',
                        data:{
                            id:userId,
                        },
                        type:'post',
                        success:function (data) {
                            if(data.code==1){
                                $('.userBox').html('<span>邀请人:</span><span>'+data.datas.realName+'</span>');
                                $('.userBox').show();
                            }
                        }
                    })
                }
                if(data.code==-1){
                    $('.userBox').hide();
                    userId = '';
                }
                if(data.code==0){
                    if(data.msg=='请输入手机号'){

                    }else{
                        mui.toast(data.msg);
                    }
                }
            }
        })

    }
}

//点击账号密码登录
$('#passlogin').click(function(){
    $('#codeloginbox').hide();
    $('#passloginbox').show();
    $('#login-button1').show();
    $('#phoneImg').attr('src','../img/login2-user.png');
    $('#phoneImg').css({'width':'14px','height':'17px'})
    $('.code-button').hide();
    $('#login-button2').hide();
    $(this).addClass('login2-active');
    $(this).siblings().removeClass('login2-active');
})

//回车登录
function keyLogin(){
    if (event.keyCode==13){
        if($('#login-button1').is(':hidden')){
            document.getElementById("login-button2").click(); //调用登录按钮的登录事件
        }else if($('#login-button2').is(':hidden')){
            document.getElementById("login-button1").click(); //调用登录按钮的登录事件
        }
    }
}

    //账号密码登录
    function loginButton1(){
        var userName = $('#phone').val();
        var passWord = $('#password').val();
        var  myArray=[];
        myArray[0]=userName;
        myArray[1]=passWord;
        var  result = ifEmpty(myArray);
        if(result==0){
            mui.toast('用户名和密码不能为空');
            return;
        }
        if(!ifCyber()){
            mui.toast('请检查网络');
        }
        $.ajax({
            url:'/user/userLoginKey.json',
            dataType:'json',
            data:{
                name:userName,
            },
            success:function(data){
                if(data.code!=1){
                    mui.toast(data.msg);
                    return;
                }
                if(data.code==1){
                    passWord= calcMD5(passWord + data.datas.userKey, 32);
                    $.ajax({
                        url:'/user/userLogin.json',
                        dataType:'json',
                        type:'post',
                        data:{
                            userName:userName,
                            passWord:remember ? getItem('passWord') :passWord,
                        },
                        success:function(data){
                            if(data.code!=1){
                                mui.toast(data.msg);
                                return;
                            }
                            if(data.code==1){
                                        setItem('token',data.datas.token);
                                        setItem('phone',userName);
                                        setItem('passWord',remember ? getItem('passWord') : passWord);
                                        window.location.href="index.html";
                            }
                        }
                    })
                }
            },
        })
    }

    //验证码登录
    function loginButton2(){
        if($('#phone').val()==""){
            mui.toast('请输入正确手机号');
            return;
        }
        if($('.code-input').val().length!=6){
            mui.toast('请输入正确验证码');
            return;
        }
        var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var n = 5, s = "";
        for(var i = 0; i < n; i++){
            var rand = Math.floor(Math.random() * str.length);
            s += str.charAt(rand);
        }
        if(!ifCyber()){
            mui.toast('请检查网络');
        }
                    $.ajax({
                        url:'/user/userLogin2.json',
                        data:{
                            userName:$('#phone').val(),
                            mobile_code:$('.code-input').val(),
                            platform:'wap',
                            upperUserId:userId,
                            isdzp:isdzp,
                        },
                        dataType:'json',
                        success:function(data){
                            if(data.code!=1){
                                mui.toast(data.msg);

                            }else{

                                        setItem('token',data.datas.token);
                                        setItem('phone',$('#phone').val());
                                        window.location.href='index.html';

                            }

                        }
                    })
    }

    //发送验证码
    $('.code-button').click(function(){
        sendCode();
    })
        function sendCode(){
            if(!$('#phone').val().match(/^1[2-9][0-9]{9}$/)){
                mui.toast('请输入正确手机号码');
                return;
            }
            if(!ifCyber()){
                mui.toast('请检查网络');
            }

            //验证该手机号是否发送过验证码
            $.ajax({
                url:'/imageVerifyC/ifCode.json',
                dataType:'json',
                data:{
                    mobile:$('#phone').val(),
                },
                type:'post',
                success:function (data) {
                    if(data.ifCode){
                        //如果为true，从本地获取图片验证码
                        verifyCode = getItem('verifyCode');
                        verify();
                    }else{
                        //如果为false，需要输入
                        var timestamp = (new Date()).valueOf();
                        $("#imgObj").attr("src","/imageVerifyC/validateCode.json?mobile="+$("#phone").val()+"&t="+timestamp);
                        $('#code_input').val('');
                        $('.zhezhao').show();
                    }
                }
            })

        }


document.getElementById('code_input').oninput=function () {
    if($(this).val().length==5){
        $.ajax({
            //验证码是否正确接口
            url:'/imageVerifyC/verifyCode.json',
            dataType:'json',
            data:{
                mobile:$('#phone').val(),
                validateCode:$('#code_input').val(),
            },
            type:'post',
            success:function (data) {
                if(data.code!=1){
                    mui.toast(data.msg);
                    return;
                }
                if(data.code==1){
                    if(data.verifyCode){
                        $('.zhezhao').hide();
                        twice=true;
                        verifyCode = $('#code_input').val();
                        setItem('verifyCode',$('#code_input').val());
                        verify();
                    }else{
                        mui.toast('验证码错误');
                        var timestamp = (new Date()).valueOf();
                        $("#imgObj").attr("src","/imageVerifyC/validateCode.json?mobile="+$("#phone").val()+"&t="+timestamp);
                        return;
                    }
                }
            }
        })
    }
}

//关闭验证窗口
$('#close').click(function () {
    $('.zhezhao').hide();
})

        function verify() {
            $(".code-button").html("发送中…");
            $(".code-button").unbind();
            $.ajax({
                url:'/user/sendMobileCode_ValidateCode.json',
                data:{
                    mobile:$('#phone').val(),
                    platform:'wap',
                    validateCode:verifyCode,

                },
                dataType:'json',
                success:function(data) {
                    if(data.code!=1){
                        if(data.msg=='图形验证码验证失败'){
                            $("#imgObj").attr("src","/imageVerifyC/validateCode.json?mobile="+$("#phone").val());
                            $('#code_input').val('');
                            $('.zhezhao').show();
                            return;
                        }
                        mui.toast(data.msg);
                        $(".code-button").html("重新发送");
                        $(".code-button").bind('click',sendCode);
                        return;
                    }
                    timeUpdate.init($(".code-button"), 60);

                }
            })
        }

        var timeUpdate = {
            node:null,//节点
            time:60,//时间
            //主函数
            start:function(){
                if(this.time > 0){
                    $(this.node).html( this.time-- + 's后重发');
                    var _this = this;
                    setTimeout(function(){
                        _this.start();
                    },1000);
                }else{
                    this.node.click(function () {
                        sendCode();
                    });
                    this.node.html("重新发送");
                }
            },
            //初始化
            init:function(node, timeLimit){
                this.node = node;
                this.time = timeLimit;
                this.start();
            }
        };


//浏览器有填充,记住密码
$(function () {
    var name = getItem('phone');
    var pass = getItem('passWord');
    if (pass != null) {
        remember = true;
        $('#phone').val(name);
        //$('#password').val(pass);
        $('#password').val('15678455545');
        $('.eye').hide();
    } else {
        remember = false;
    }

});
$('#phone').keydown(function () {
    remember = false;
});
$('#password').keydown(function () {
    remember = false;
});

//清除按钮隐藏显示
document.getElementById('phone').oninput=function(){
    //document.activeElement.scrollIntoViewIfNeeded();
    if($(this).val()==""||$(this).val()=='请输入手机号'){
        $('.clear').hide();
    }else{
        $('.clear').show();
    }
    if($(this).val().length==11){
        $('#password').focus();
    }
}
//清除按钮清除输入框内容
$('.clear').click(function(){
    $('#phone').val('');
})
//密码明文
$('.eye').click(function(){
    if($('#password').attr('type')=='text'){
        $('#password').attr('type','password');
        $('.eye').css({'background':'url("../img/eye-hide.png") no-repeat 0 0','background-size':'17px 8.5px','width':'17px','height':'8.5px','top':'26px'})
    }else{
        $('#password').attr('type','text');
        $('.eye').css({'background':'url("../img/eye-show.png") no-repeat 0 0','background-size':'18px 9px','width':'18px','height':'9px','top':'22px'})
    }
})
//同意协议
$('#agreeicon').click(function(){
    if($(this).attr('src')=='../img/agree.png'){
        $(this).attr('src','../img/noAgree.png');
        $('#login-button1').css('pointer-events','none');
        $('#login-button2').css('pointer-events','none');
    }else{
        $(this).attr('src','../img/agree.png');
        $('#login-button1').css('pointer-events','auto');
        $('#login-button2').css('pointer-events','auto');
    }
})